package cn.hc.tool.exec.aspect;

import cn.hc.tool.common.util.StringUtil;
import com.hc.json.adapter.Json;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/9/24 19:38
 */
@Aspect
@Slf4j
@Component
@PropertySource(value = {"classpath:important.properties"}, encoding = "utf-8", ignoreResourceNotFound = true)
public class AdministratorAspect {

    @Value("${hc.security.code:}")
    private String securityCode;

    @Around("@annotation(cn.hc.tool.exec.aspect.Administrators) or @within(cn.hc.tool.exec.aspect.Administrators)")
    public Object controllerAround(ProceedingJoinPoint pjp) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        if (request == null || StringUtil.isBlank(securityCode) || !securityCode.equals(request.getParameter("securityCode"))) {
            log.error("非法请求：{}", request == null ? null : request.getParameter("securityCode"));
            Map<String, Object> m = new HashMap<String, Object>();
            m.put("success", false);
            m.put("data", "No authority!");
            return Json.toJson(m);
        }
        log.info("{}#{},开始执行", getClassName(pjp), getMethodName(pjp));
        return pjp.proceed();
    }

    private String getClassName(JoinPoint jp) {
        return jp.getSignature().getDeclaringTypeName();
    }

    private String getMethodName(JoinPoint jp) {
        return jp.getSignature().getName();
    }

}
